<template>
  <el-dialog
    custom-class="insert-organization-dialog"
    title="新增用户"
    :visible.sync="dialogVisible"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    @open="dialogOpenHandler"
    @close="dialogCloseHandler">
    <el-form class="insert-form"
             label-width="120px"
             ref="insertFormRef"
             :rules="rules"
             :model="userModel"
             label-suffix=":">
      <el-row>
        <el-col :xs="24" :sm="12">
          <el-form-item label="组织编码" prop="orgCode">
            <el-input v-model="userModel.orgCode" placeholder="请输入组织编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="userModel.realName" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="userModel.userName" placeholder="请输入用户名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model="userModel.password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="手机号码" prop="mobileNo">
            <el-input v-model="userModel.mobileNo" placeholder="请输入手机号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="userModel.email" placeholder="请输入邮箱地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="是否有效" prop="valid">
            <el-switch v-model="userModel.valid" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :xs="28" :sm="24">
          <el-form-item label="用户描述" prop="remark">
            <el-input type="textarea" :row="6" v-model="userModel.remark" placeholder="请输入用户描述" maxlength="500"
                      show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitHandler">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>

  import {validateUserExistApi, updateUserApi} from '@/api/user'

  export default {
    name: "insertUserDialog",
    data() {
      /**
       * 组织机构编码验证器
       * @param rule
       * @param value
       * @param callback
       */
      var validateUserName = (rule, value, callback) => {
        //如果验证的用户名与之前的用户名相等，则不做接口验证（有可能是修改其他属性，用户名不变）
        if (value === this.oldUserModel.userName) {
          return callback();
        }
        let params = {
          userName: this.userModel.userName,
        }
        validateUserExistApi(params).then(response => {
          if (response.msg === '校验通过') {
            return callback();
          } else if (response.msg === '该用户已存在') {
            return callback('该用户已存在');
          }
        })
      }

      return {
        dialogVisible: false,
        oldUserModel: {},
        userModel: {
          orgCode: '',
          userName: '',
          realName: '',
          password: '',
          mobileNo: '',
          email: '',
          remark: '',
          valid: 1,
        },
        rules: {
          orgCode: [
            {required: true, message: '组织编号不可为空', trigger: 'blur'}
          ],
          realName: [
            {required: true, message: '姓名不可为空', trigger: 'blur'}
          ],
          userName: [
            {required: true, message: '用户名不可为空', trigger: 'blur'},
            {validator: validateUserName, trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不可为空', trigger: 'blur'}
          ],
          mobileNo: [
            {pattern: /^1\d{10}$/, message: "请输入正确的手机号"}
          ],
          email: [
            {pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/, message: "请输入正确的邮箱地址"}
          ]
        }
      }
    },
    methods: {
      //获取需要编辑的用户信息
      setUserModelHandler(user = {}) {
        this.oldUserModel = Object.assign({}, user)
        this.userModel = Object.assign({}, user)
      },

      /**
       * 启用对话框
       */
      enabledDialogHandler() {
        this.dialogVisible = true
      },
      /**
       * 关闭对话框
       */
      disabledDialogHandler() {
        this.dialogVisible = false
      },
      /**
       * 对话框打开回调处理
       */
      dialogOpenHandler() {

      },
      /**
       * 对话框关闭回调处理
       */
      dialogCloseHandler() {

      },
      /**
       * 提交操作
       */
      submitHandler() {
        this.$refs.insertFormRef.validate().then(valid => {
          updateUserApi(this.userModel).then(response => {
            if (response.result) {
              this.$message({
                type: 'success',
                message: '编辑用户成功！'
              });
              this.disabledDialogHandler()
              this.$refs['insertFormRef'].resetFields()
              this.$emit('updateSuccessEvent')
            }
          }).catch(error => {
          })
        }).catch(valid => {

        })
      }
    }
  }
</script>

<style scoped lang="scss">

  .insert-organization-dialog {
  }

</style>
